import { Modal as AntdModal, Form, Button, message, Tag, Spin } from 'antd';
import { useRequest } from 'umi';
import { useEffect } from 'react';
import moment from 'moment';
import FormBuilder from '../builder/FormBuilder';
import ActionBuilder from '../builder/ActionBuilder';

import { setFieldsAdaptor, submitFieldsAdaptor } from '../helper';
import styles from '../index.less';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const Modal = (props: any) => {
  const { modalVisible, hideModal, handleOk, modalUrl } = props;

  const [form] = Form.useForm();

  const init = useRequest<{ data: BasicListApi.PageData }>(
    `https://public-api-v2.aspirantzhang.com${modalUrl}?X-API-KEY=antd`,
    {
      manual: true,
    },
  );

  // 请求
  const request = useRequest(
    (values: any) => {
      message.loading({ content: 'Processing...', key: 'process', duration: 0 });
      console.log(values);
      const { uri, method, formValues } = values;
      return {
        url: `https://public-api-v2.aspirantzhang.com${uri}`,
        method,
        data: {
          ...submitFieldsAdaptor(formValues),
          'X-API-KEY': 'antd',
          create_time: moment(formValues.create_time).format(),
          update_time: moment(formValues.update_time).format(),
        },
      };
    },
    {
      manual: true,
      onSuccess: (data) => {
        message.success({
          content: data.message,
          key: 'process',
        });
        hideModal(true);
      },
      formatResult: (res: any) => {
        return res;
      },
    },
  );

  useEffect(() => {
    if (modalVisible) {
      init.run();
    }
  }, [modalVisible]);

  useEffect(() => {
    if (init.data) {
      form.setFieldsValue(setFieldsAdaptor(init.data));
    }
  }, [init.data]);

  // 按钮渲染
  const actionHandler = (action: BasicListApi.Action) => {
    switch (action.action) {
      case 'submit':
        request.run({
          uri: action.uri,
          method: action.method,
          formValues: form.getFieldsValue(true),
        });
        break;
      case 'cancel':
        hideModal();
        break;
      case 'reset':
        form.resetFields();
        break;

      default:
        break;
    }
  };

  return (
    <AntdModal
      forceRender
      title={init?.data?.page.title}
      visible={modalVisible}
      onOk={handleOk}
      onCancel={() => {
        hideModal();
      }}
      footer={ActionBuilder(init?.data?.layout?.actions[0].data, actionHandler, request.loading)}
      afterClose={() => {
        form.resetFields();
      }}
    >
      {init?.loading ? (
        <Spin className={styles.formSpin} tip="Loading..." />
      ) : (
        <Form
          {...formItemLayout}
          form={form}
          initialValues={{ create_time: moment(), update_time: moment(), status: true }}
        >
          <Button
            onClick={() => {
              form.submit();
            }}
          ></Button>
          {FormBuilder(init?.data?.layout?.tabs[0].data)}
          <Tag className={styles.formUpdateTime}>
            Update Time: {moment(form.getFieldValue('update_time')).format('YYYY-MM-DD HH:mm:ss')}
          </Tag>
        </Form>
      )}
    </AntdModal>
  );
};
export default Modal;
